/*
AlliedBridge Content Management System
Copyright (C) 2006 AlliedBridge

This program is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation;

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.volume4.alliedbridge.model.events;

import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.*;
import org.volume4.utils.ServletUtilities;

/**
 * @author Schalk
 */
public class UpdateEvent extends HttpServlet {

    // Should the following three String declarations be private or final?
    // Should they be in an interface?
    public String DRIVER, URL, USER, PASS, fieldName, fieldData, fileName, fileFieldName;
    public String folder = "c:\\tomcat\\webapps\\modelcup\\media\\comp_logos\\";
    public String entryFormFolder = "c:\\tomcat\\webapps\\modelcup\\media\\docs\\entry_forms\\";
    public String tempFolder = "c:\\temp\\";
    //public String folder = "/opt/tomcat5/webapps/mc/media/comp_logos/";
    //public String entryFormFolder = "/opt/tomcat5/webapps/mc/media/docs/entry_forms/";
    //public String tempFolder = "/opt/tomcat5/webapps/mc/media/temp/";
    public String app_root, messageSuccess, messageFail;
    public String event_id, series, level_status, total_points, comp_name, place, venue, region, start_date, end_date,
    start_time, end_time, comp_logo, current_comp_logo, lb_comp_logo, current_lb_comp_logo, entry_form, current_entry_form;

    /* The parameters below would need to be set via a properties or XML
     * configuration file per company dependant on which company 
     * are accessing these methods.
     * 
     * There may be a better way to do this and this should be
     * investigated.
    */
    public void init() throws ServletException {
        ServletContext context = getServletContext();
        DRIVER = context.getInitParameter("driver");
        URL = context.getInitParameter("mc_dburl");
        USER = context.getInitParameter("mc_dbuser");
        PASS = context.getInitParameter("mc_dbpass");
    }

    public void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Connection con = null;
        messageSuccess = "Update of event completed successfuly.";
        messageFail = "Update of event failed.";

        try {

            DiskFileUpload upload = new DiskFileUpload();
            upload.setSizeThreshold(4096);
            upload.setRepositoryPath(tempFolder);
            upload.setSizeMax(-1);

            // Parse the request
            List fileItems = upload.parseRequest(request);

            // Process the uploaded fields
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("id")) {
                        event_id = item.getString();
                    } else if (item.getFieldName().equals("series")) {
                        series = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("level_status")) {
                        level_status = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("total_points")) {
                        total_points = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("comp_name")) {
                        comp_name = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("place")) {
                        place = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("venue")) {
                        venue = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("region")) {
                        region = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("start_date")) {
                        start_date = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("end_date")) {
                        end_date = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("start_time")) {
                        start_time = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("end_time")) {
                        end_time = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("current_comp_logo")) {
                        current_comp_logo = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("current_lb_comp_logo")) {
                        current_lb_comp_logo = ServletUtilities.filter(item.getString());
                    } else if (item.getFieldName().equals("current_entry_form")) {
                        current_entry_form = ServletUtilities.filter(item.getString());
                    }
                } else {
                    if (item.getFieldName().equals("comp_logo")) {

                        int i = item.getName().lastIndexOf('\\');
                        comp_logo = ServletUtilities.filter(item.getName().substring(i + 1));

                        if(comp_logo == null) {
                             comp_logo = current_comp_logo;
                        } else {
                        File savedFile = new File(folder, ServletUtilities.filter(item.getName().substring(i + 1)));
                        item.write(savedFile);
                        }

                    } else if (item.getFieldName().equals("lb_comp_logo")) {

                        int i = item.getName().lastIndexOf('\\');
                        lb_comp_logo = ServletUtilities.filter(item.getName().substring(i + 1));

                        if(lb_comp_logo == null) {
                            lb_comp_logo = current_lb_comp_logo;
                        }
                        File savedFile = new File(folder, ServletUtilities.filter(item.getName().substring(i + 1)));
                        item.write(savedFile);

                    } else if (item.getFieldName().equals("entry_form")) {

                        int i = item.getName().lastIndexOf('\\');
                        entry_form = ServletUtilities.filter(item.getName().substring(i + 1));

                        if(entry_form == null) {
                            entry_form = current_entry_form;
                        }
                        File savedFile = new File(entryFormFolder, ServletUtilities.filter(item.getName().substring(i + 1)));
                        item.write(savedFile);

                    }
                }

                Class.forName(DRIVER);
                con = DriverManager.getConnection(URL, USER, PASS);
                Statement stmt = con.createStatement();

                String EventUpdateQuery = "UPDATE ab_events_calendar SET " +
                        "series= '" + series + "' ," +
                        "level_status= '" + level_status + "', " +
                        "total_points= '" + total_points + "', " +
                        "comp_logo= '" + comp_logo + "', " +
                        "comp_name= '" + comp_name + "', " +
                        "lb_comp_logo= '" + lb_comp_logo + "', " +
                        "place= '" + place + "', " +
                        "venue= '" + venue + "', " +
                        "region= '" + region + "', " +
                        "start_date= '" + start_date + "', " +
                        "end_date= '" + end_date + "', " +
                        "start_time= '" + start_time + "', " +
                        "end_time= '" + end_time + "', " +
                        "entry_form= '" + entry_form + "' " +
                        "WHERE id ='" + event_id + "'";

                int result = stmt.executeUpdate(EventUpdateQuery);

                app_root = request.getContextPath();
                response.sendRedirect(app_root + "/application/application_messages/process_result.jsp?message=" + messageSuccess);
            }

        } catch (SQLException ex) {
            out.println("\nERROR:------ SQLException -----\n");
            while (ex != null) {
                out.println("Message: " + ex.getMessage() + "<br>");
                out.println("SQLState: " + ex.getSQLState() + "<br>");
                out.println("ErrorCode :" + ex.getErrorCode());
                ex = ex.getNextException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (con != null)
                    con.close();
            } catch (SQLException ex) {
                out.println("\nERROR:------ SQLException -----\n");
                out.println("Message: " + ex.getMessage());
                out.println("SQLState: " + ex.getSQLState());
                out.println("ErrorCode :" + ex.getErrorCode());
            }
        }
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request  servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request  servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

}